package logic

import (
	"context"
	"fmt"
	"github.com/google/uuid"
	"order_srv/order_srv"

	"api/internal/svc"
	"api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateOrderLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewCreateOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateOrderLogic {
	return &CreateOrderLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

const vipPrice = 100 //折扣价格
var price = 500.00   //测试价格

func (l *CreateOrderLogic) CreateOrder(req *types.CreateOrderRequest) (resp *types.Response, err error) {
	// todo: add your logic here and delete this line

	_, err = l.svcCtx.OrderSrv.FindUser(l.ctx, &order_srv.FindUserRequest{UserId: int64(req.UserId)})

	fmt.Println(err)

	if err != nil {
		return &types.Response{
			Message: "订单创建失败,用户不存在",
			Code:    500,
			Data:    nil,
		}, nil
	}

	_, err = l.svcCtx.OrderSrv.FindUserStatus(l.ctx, &order_srv.FindUserStatusRequest{UserId: int64(req.UserId)})

	if err != nil {
		return &types.Response{
			Message: "订单创建失败,用户状态错误",
			Code:    500,
			Data:    nil,
		}, nil
	}

	amount := (float64(req.Num) * price) - vipPrice

	orders := uuid.NewString()
	fmt.Println(orders)

	order, err := l.svcCtx.OrderSrv.CreateOrder(l.ctx, &order_srv.CreateOrderRequest{
		UserId:   int64(req.UserId),
		Payment:  req.Payment,
		Price:    float32(price),
		VipPrice: vipPrice,
		Num:      int64(req.Num),
		Amount:   float32(amount),
		OrderSn:  orders,
	})
	if err != nil {
		return &types.Response{
			Message: "订单创建失败",
			Code:    500,
			Data:    nil,
		}, nil
	}

	pay, err := l.svcCtx.OrderSrv.AliPay(l.ctx, &order_srv.AliPayRequest{
		Title:   order.Title,
		OrderSn: order.OrderSn,
		Amount:  order.Amount,
	})

	if err != nil {
		return &types.Response{
			Message: "订单创建失败",
			Code:    500,
			Data:    nil,
		}, nil
	}

	return &types.Response{
		Message: "订单创建成功",
		Code:    200,
		Data:    pay,
	}, nil
}
